package DAO;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
//import android.database.Cursor;
//import android.database.SQLException;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
	public static int _defaultNumber = 0;
	protected static boolean FLAG = false;
	private final Context _myContext;
	Context _mContext;
	String _fullPath = "/data/data/Nhom7.mainPackage.main/databases/data1";
	static SQLiteDatabase _myDataBase;

	public DatabaseHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		_myContext = context;
	}

	@Override
	public void onCreate(SQLiteDatabase arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	public void checkAndCopyDatabase() throws IOException {
		boolean dbExist = checkDataBase();
		if (dbExist) {
			copyDataBase();
			Log.d("TAG", "database already exist!");
		} else {
			this.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
				Log.d("TAG", "Error copying database");
			}
		}
	}

	private boolean checkDataBase() {
		SQLiteDatabase _checkDB = null;
		try {
			_checkDB = SQLiteDatabase.openDatabase(_fullPath, null,
					SQLiteDatabase.OPEN_READWRITE);
		} catch (SQLiteException e) {
		}
		if (_checkDB != null)
			_checkDB.close();
		return _checkDB != null ? true : false;
	}

	private void copyDataBase() throws IOException {
		InputStream _myInput = _myContext.getAssets().open("data.db");
		OutputStream _myOutput = new FileOutputStream(_fullPath);
		byte[] _buffer = new byte[1024];
		int _length;
		while ((_length = _myInput.read(_buffer)) > 0) {
			_myOutput.write(_buffer, 0, _length);
		}
		_myOutput.flush();
		_myOutput.close();
		_myInput.close();
	}

	protected static Object getDataRowFromDataReader(Cursor cursor) {
		return null;
	}

	public void open() {
		try {
			_myDataBase = SQLiteDatabase.openDatabase(_fullPath, null,
					SQLiteDatabase.OPEN_READWRITE);
			_myDataBase.setLocale(new Locale("vi"));

		} catch (SQLiteException ex) {
			ex.printStackTrace();
			Log.i("aaa", "There is no valid dictionary database " + " at path ");
		}
	}

	@Override
	public void close() {
		if (_myDataBase != null)
			_myDataBase.close();
		super.close();
	}
}